package com.bdmc.app.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.bdmc.app.model.AppLoginModel;
import com.bdmc.app.service.AppLoginService;
import com.bdmc.base.domain.BasePerson;
import com.bdmc.common.constant.Constants;
import com.bdmc.common.core.domain.AjaxResult;
import com.bdmc.common.core.domain.model.LoginUser;
import com.bdmc.common.exception.ServiceException;
import com.bdmc.common.utils.LoginUtils;
import com.bdmc.common.utils.StringUtils;
import com.bdmc.common.utils.wechat.OAuthOpenid;
import com.bdmc.common.utils.wechat.WeChatMiniUtil;
import com.bdmc.system.service.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("app/user/")
public class UserController {
    @Autowired
    WeChatMiniUtil wechatUtil;

    @Autowired
    AppLoginService loginService;

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @PostMapping("/login")
    public AjaxResult<Map<String, Object>> doLogin(@RequestBody AppLoginModel loginModel) throws Exception{
        OAuthOpenid oauth = wechatUtil.GetWXOpenidInfo(loginModel.getJscode());
        String openid = oauth.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            throw new ServiceException("登录失败，openid为空");
        }
        loginModel.setOpenid(openid);
        String sessionKey = oauth.getSession_key();
        String mobile = wechatUtil.decryptPhoneNumber(loginModel.getEncryptedData(), sessionKey, loginModel.getIv());
        loginModel.setMobile(mobile);
        String token = loginService.appLogin(loginModel);
        if(StringUtils.isEmpty(token)){
            throw new ServiceException("登录失败,非法用户！");
        }
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        ajax.put(Constants.TOKEN, token);
        return AjaxResult.success(ajax);
    }


    /**
     * 获取当前登录用户信息
     * @return person
     */
    @GetMapping("info")
    public AjaxResult<BasePerson> info() {
        return AjaxResult.success(loginService.getCurrentLoginPerson());
    }

    /**
     * 登出
     * @return 结果
     */
    @PostMapping("logout")
    public AjaxResult<Void> logout() {
        try {
            StpUtil.logout();
        } catch (NotLoginException e) {
            log.error(e.getMessage());
        }
        return AjaxResult.success("退出成功");
    }
}
